<script setup lang="ts">
import { useGlobalState } from './stores/global'
import { storeToRefs, watch } from 'pinia'

const globalStore = useGlobalState()
const { userInfo } = storeToRefs(globalStore)

// 导入qiankun的actions
import { actions } from './micro/index'

// 添加全局状态变化监听
// 当子应用更新全局状态时，同步更新主应用的Pinia store
actions.onGlobalStateChange((state, prevState) => {
  console.log('主应用接收到全局状态变化:', state, prevState)
  if (state.userInfo && JSON.stringify(state.userInfo) !== JSON.stringify(userInfo.value)) {
    globalStore.changeUserInfo(state.userInfo)
  }
}, true)

// 修改用户信息的示例函数
const updateUserInfo = () => {
  const newUserInfo = {
    name: '李四',
    age: 20
  }
  globalStore.changeUserInfo(newUserInfo)
  // 同步更新qiankun的全局状态
  actions.setGlobalState({ userInfo: newUserInfo })
}
</script>

<template>
  <div class="main-container">
    <header>
      <h1>微前端主应用</h1>
      <div class="user-info">
        当前用户：{{ userInfo.name }}, {{ userInfo.age }}岁
        <button @click="updateUserInfo">更新用户信息</button>
      </div>
    </header>
    
    <nav>
      <router-link to="/app1/home">App1 - Home</router-link>
      <router-link to="/app1/about">App1 - About</router-link>
      <router-link to="/app2/home">App2 - Home</router-link>
      <router-link to="/app2/about">App2 - About</router-link>
      <router-link to="/app3/home">App3 - Home</router-link>
      <router-link to="/app3/about">App3 - About</router-link>
    </nav>
    
    <main>
      <router-view />
      <div id="micro-app-container"></div>
    </main>
  </div>
</template>

<style scoped>
.main-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

button {
  padding: 5px 10px;
  background-color: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

nav {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

router-link {
  text-decoration: none;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f0f0f0;
  color: #333;
}

router-link:hover {
  background-color: #e0e0e0;
}

main {
  min-height: 400px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
}
</style>
